package com.sagittariusjin.android.serialportbecoroutinelib;

import android.util.Log
import  com.sagittariusjin.android.serialportbecoroutinelib.bean.ResultSerialBean
import  com.sagittariusjin.android.serialportbecoroutinelib.bean.SerialBean
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

internal class SerialPortDispatch {
    private lateinit var serialPort: SerialPort;
    var receivechannel: Channel<SerialBean> = Channel()
    var backchannel: Channel<ResultSerialBean> = Channel(UNLIMITED)
    private  val TAG = "SerialPortCoroutine"
    @Volatile
    var flag = true

    /**
     * 传入 串口对象为空 自动默认 地址为 /dev/ttyS3 波特率为9600
     * @param serialPort SerialPort?
     * @constructor
     */
    constructor(serialPort: SerialPort?) {
        if (serialPort != null) {
            this.serialPort = serialPort
        } else {
            this.serialPort = SerialPort(File("/dev/ttyS3"), 9600, 0)
        }

        SerialHttpThread().start()

    }

    /*suspend fun asdfd(){
        GlobalScope.launch {

             backchannel =  produce<ResultSerialBean> {
                Log.i("线程开始","${Thread.currentThread()},gouguo")
                while (true) {
                    try {

                        delay(200)
                        var serialNumber = -1

                        receivechannel?.apply {
                            if (!isClosedForReceive && !isEmpty) {

                                var bean = this.receive()
                                serialNumber = bean.serialNumber

                                serialPort?.outputStream.write(bean.content)
                                serialPort?.outputStream.flush()
                            }
                        }
                        delay(300)
                        if (serialPort != null && serialPort.inputStream != null) {
                            var buffer = ByteArray(64)
//                            var buffer = byteArrayOf(0x00,0x00)

                            var size = serialPort.inputStream.available()
                            println("::::1")
//                            var size = 0
                            if (size > 0) {
                                println("::::2")
                                serialPort.inputStream.read(buffer)
                                var buffersend = ByteArray(size)
                                System.arraycopy(buffer,0,buffersend,0,size)
                                println("::::3")
                                isReviceState = 1
                                send(
                                    ResultSerialBean(
                                        serialNumber = serialNumber,
                                        content =buffersend,
                                        code = 200
                                    )
                                )
                                println("::::4")
                                serialNumber = -1
                            } else {
                                println("::::")
//                                if (serialNumber!=-1) {
//                                    backchannel?.send(ResultSerialBean(serialNumber = serialNumber, code = 500))
//
//                                }
                            }
                        }else{
                            Log.i(TAG,"串口对象为空")
                        }

                    }catch (e:Exception){
                        Log.i(TAG,"${e.message}")
                    }

                }


            }
        }
    }*/


    inner class SerialHttpThread : Thread("HTTP") {


        override fun run() {
            GlobalScope.launch {
                Log.i(TAG, "读写线程开始---${currentThread()}")
                while (flag) {
                    try {
                        var serialNumber = -1
                            if (!receivechannel.isClosedForReceive && !receivechannel.isEmpty) {
                                val bean = receivechannel.receive()
                                serialNumber = bean.serialNumber
                                serialPort.outputStream.write(bean.content)
                                serialPort.outputStream.flush()
                            }

                        delay(500)
                        if (serialPort != null && serialPort.inputStream != null) {
                            var buffer = ByteArray(64)
//                            var buffer = byteArrayOf(0x00,0x00)

                            var size = serialPort.inputStream.available()

                            if (size > 0) {

                                serialPort.inputStream.read(buffer)
                                var buffersend = ByteArray(size)
                                System.arraycopy(buffer, 0, buffersend, 0, size)

                                backchannel.send(
                                    ResultSerialBean(
                                        serialNumber = serialNumber,
                                        content = buffersend,
                                        code = 200
                                    )
                                )
                                serialNumber = -1
                            } else {
//                                println("::::")
//                                if (serialNumber!=-1) {
//                                    backchannel?.send(ResultSerialBean(serialNumber = serialNumber, code = 500))
//
//                                }
                            }
                        } else {
                            Log.e(TAG, "串口对象为空")
                        }

                    } catch (e: Exception) {
                        Log.e(TAG, "${e.message}")
                    }

                }
                Log.i(TAG, "-------读写线程逻辑结束")
            }

        }

        override fun destroy() {
//            super.destroy()
            Log.i(TAG, "读取线程结束")
        }
    }

    fun close() {
        flag = false

    }
}
